package com.jyl.data.impl;

import com.jyl.data.List;

import java.util.function.Consumer;

/**
 * @ClassName DynamicArray
 * @Author admin
 * @Date 2024/6/11
 */
public class DynamicArray<E> implements List<E> {

    private int size = 0;

    private static final int INITIAL_CAPACITY = 5;

    private Object[] array;

    public DynamicArray(){
        this.array = new Object[INITIAL_CAPACITY];
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return array.length == 0;
    }

    @Override
    public void add(E element) {
        add(size,element);
    }

    /**
     * 数组扩容
     */
    public void grow(){
        int len = array.length;
        Object[] newArray =  new Object[len * 2];
        for (int i = 0; i < len; i++) {
            newArray[i] = array[i];
        }
        array = newArray;
    }

    @Override
    public void add(int index, E element) {
        // 1.验证index是否合法
        if (index < 0 || index > size) {
            throw new ArrayIndexOutOfBoundsException(index);
        }

        // 2.数组扩容逻辑
        if (size >= array.length) {
            grow();
        }

        // 3.根据index插入 , 倒序遍历
        for (int i = size - 1;i >= index;i--) {
            array[i + 1] = array[i];
        }
        array[index] = element;
        size++;
    }

    @Override
    public E get(int index) {
        if (index < 0 || index >= size){
            throw new ArrayIndexOutOfBoundsException(index);
        }
        return (E) array[index];
    }

    @Override
    public E remove(int index) {
        if (index < 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException(index);
        }

        Object target =  array[index];
        for (int i = index; i < size - 1; i++) {
            array[i] = array[i + 1];
        }
        array[--size] = null;
        return (E) target;
    }

    @Override
    public E set(int index, E element) {
        if (index < 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        Object target = array[index];
        array[index] = element;
        return (E) target;
    }

    @Override
    public void forEach(Consumer<E> consumer) {
        for (int i = 0; i < size; i++) {
            consumer.accept((E) array[i]);
        }
    }

    public String toString(){
        StringBuilder builder = new StringBuilder();
        builder.append("[");
        for (int i = 0; i < size; i++) {
            builder.append(array[i]).append(i == size - 1 ? "" : ",");
        }
        builder.append("]");
        return builder.toString();
    }















}
